#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "mylog.hpp"

#define SIZE 1024
Log lg;

enum{
    SOCKETERR = 1,
    BINDERR,
    IOERR
};


int main(int num,char * args[])
{
    if(num != 3)
    {
        std::cout << "./udpclient server port" << std::endl;
        exit(IOERR);
    }

    uint16_t port = std::stoi(args[2]);
    std::string ip = args[1];

    int sockfd =socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd == -1)
    {
        lg(FATAL,"套接字申请失败,errno:%d",errno);
        exit(SOCKETERR);
    }
    lg(INFO,"套接字申请成功,errno:%d",errno);

    struct sockaddr_in local;
    bzero(&local,sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = inet_addr(ip.c_str());

    
    char buf[SIZE];
    socklen_t len = sizeof(local);
    std::string str;
    while(true)
    {
        std::cout << "请发送:";
        std::getline(std::cin,str);

        ssize_t n = sendto(sockfd,str.c_str(),str.size(),0,(const sockaddr*)(&local),len);
        if(n == -1)
        {
            lg(WARNING,"发送数据失败,errno:%d",errno);
            continue;
        }


        ssize_t ret = recvfrom(sockfd,buf,sizeof(buf) - 1,0,(sockaddr *)(&local),&len);
        if(ret == -1)
        {
            lg(WARNING,"接收数据失败,errno:%d",errno);
            continue;
        }

        buf[ret] = 0;
        std::cout << buf << std::endl;

    }

    return 0;
}